#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

typedef int ElemType;

typedef struct Node
{
    ElemType data;
    struct Node *next;
} Node, *Node_t;

// 初始化结构体
bool InitList(Node_t *p)
{
    *p = calloc(1, sizeof(Node));
    if (*p == NULL)
    {
        printf("%s,%d:calloc false\n", __FUNCTION__, __LINE__);
        return false;
    }
    (*p)->next = NULL;
    (*p)->data = 0; // 头结点的数据域用来存储节点的个数
    return true;
}

// 头插
bool HeadAddList(Node_t p, ElemType n)
{
    if (p == NULL)
    {
        return false;
    }
    Node_t newnode = calloc(1, sizeof(Node));
    if (newnode == NULL)
    {
        printf("%s,%d:calloc false\n", __FUNCTION__, __LINE__);
    }
    newnode->data = n;
    newnode->next = p->next;
    p->next = newnode;
    p->data++;
    // printf("%d\n",p->data);
    return true;
}

// 尾插
bool TailAddList(Node_t p, ElemType n)
{
    if (p == NULL)
    {
        return false;
    }
    Node_t newnode = calloc(1, sizeof(Node));
    if (newnode == NULL)
    {
        printf("%s,%d:calloc false\n", __FUNCTION__, __LINE__);
    }
    if (p->next==NULL)
    {
        newnode->data = n;
        newnode->next = p->next;
        p->next = newnode;
        p->data++;
        // printf("%d\n",p->data);
        return true;
    }
    else
    {
        Node_t q = p->next;
        while (q->next!=NULL)
        {
            q= q->next;
        }
        newnode->data = n;
        newnode->next = q->next;
        q->next = newnode;
        p->data++;
        // printf("%d\n",p->data);
    }

    return true;
}

//头删
bool HeadDelList(Node_t p)
{
    if (p->next==NULL)
    {
        return false;
    }
    Node_t q = p->next;
    Node_t e = p->next;
    p->next = q->next; 
    p->data--;
    // printf("%d\n",p->data);
    free(e);
}

//尾删
bool TailDelList(Node_t p)
{
    if (p->next==NULL)
    {
        return false;
    }
    Node_t q = p->next;
    Node_t w = p->next;
    while (w->next!=NULL)
    {
        q = q->next;
        w = q->next;
    }
    q->next = NULL;
    p->data--;
    // printf("%d\n",p->data);
    free(w);
    return true;
}

// 遍历
bool ShowList(Node_t p)
{
    if (p == NULL)
    {
        return false;
    }
    Node_t q = p->next;
    while (q != NULL)
    {
        printf("%d||\t", q->data);
        q = q->next;
    }
    printf("\n");
    return true;
}

int main(int argc, char const *argv[])
{
    Node_t head = NULL;
    // 初始化结构体
    InitList(&head);

    // 头插
     HeadAddList(head,1);
     HeadAddList(head,2);
     HeadAddList(head,3);
     HeadAddList(head,4);
     HeadAddList(head,5);

    // 尾插
    // TailAddList(head, 1);
    // TailAddList(head, 2);
    // TailAddList(head, 3);
    // TailAddList(head, 4);
    // TailAddList(head, 5);
    ShowList(head);

    //头删
    // HeadDelList(head);

    //尾删
    TailDelList(head);

    // 遍历
    ShowList(head);

    return 0;
}
